package javax.core.common.mongo;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import javax.core.common.utils.GenericsUtils;
import java.io.Serializable;
import java.util.List;

@SuppressWarnings("ALL")
public abstract class BaseDaoSupport<T extends Serializable, PK extends Serializable> {

    private MongoTemplate mongoTemplate;
    private final EntityOperation<T> entityOperation;

    public BaseDaoSupport() {
        Class entityClass = GenericsUtils.getSuperClassGenericType(getClass(), 0);
        entityOperation = new EntityOperation<T>(entityClass);
    }

    protected void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    protected abstract String getPKColumn();

    protected List<T> find(QueryRule queryRule) {
        QueryRuleBuilder builder = new QueryRuleBuilder(queryRule);
        Query query = builder.getQuery();
        return mongoTemplate.find(query, entityOperation.entityClass);
    }

    protected int saveAll(List<T> list) {
        mongoTemplate.insertAll(list);
        return list.size();
    }

    protected T get(PK id) {
        QueryRule queryRule = QueryRule.getInstance();
        queryRule.andEqual(this.getPKColumn(), id);
        QueryRuleBuilder bulider = new QueryRuleBuilder(queryRule);
        Query query = bulider.getQuery();
        return mongoTemplate.findOne(query, entityOperation.entityClass);
    }

    protected int delete(T entity) {
        return mongoTemplate.remove(entity).getN();
    }

}
